package com.apkfuns.jsbridge.view;

import com.apkfuns.jsbridge.util.CameraUtil;
import com.apkfuns.jsbridge.util.TakePhotoResult;
import com.apkfuns.jsbridge.util.WebEvent;
import com.apkfuns.jsbridge.view.slice.CustomFragmentAbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.File;

public class CustomFragmentAbility extends FractionAbility  implements WebEvent  {
    public static final String TAG = "CustomFragmentAbility";
    private static final HiLogLabel LABEL = new HiLogLabel(0, 0, "CustomFragmentAbility");
    private TakePhotoResult result;
    private String imagePath;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(CustomFragmentAbilitySlice.class.getName());
    }

    @Override
    public void takePhoto(TakePhotoResult r) {

        this.result = r;
        imagePath = getExternalCacheDir().getPath() + File.separator+"picture_002.jpg";
        File outputImage = new File(imagePath);
        if (outputImage.exists()) {
            try {
                outputImage.delete();
            } catch (SecurityException  e){

            }
        }


        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.apkfuns.jsbridge.view.CameraAbility")
                .build();
        intent.setOperation(operation);

        intent.setParam("imagePath", imagePath);
        startAbilityForResult(intent,0);


    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == 0 && imagePath!=null) {

             String imageBase64Data =  CameraUtil.imageFileToBase64String(imagePath);
            HiLog.info(LABEL, "imageBase64Data " + imageBase64Data);
            if (result != null) {

                result.onSuccess(imageBase64Data);
            }
        } else {
            if (result != null) {
                result.onFailure("user cancel");
            }
        }
    }


}
